const _=require('underscore');
const {Post,User,Comment}=require('../models/index');
const config=require('../config/config');

module.exports={
    findFull:async (query,fields,opts)=>{
        let ret=await Post.page(query,fields,opts);

        if(!ret.posts.length)return ret;

        let {posts}=ret;
        let authors=await Promise.all(posts.map(post=>User.findOne({_id:post.author},{_id:true,name:true,email:true,avatar:true})));

        let comments=await Promise.all(posts.map(post=>Promise.all(post.comments.map(_id=>Comment.findOne({_id},{_id:false,author:true,content:true,time:true})))));
        let commentAuthors=await Promise.all(
            comments.map(postComments=>Promise.all(
                postComments.map(comment=>User.findOne({_id:comment.author},{name:true,email:true,avatar:true}))
            ))
        );
        comments.forEach((postComments,i)=>{
            postComments.forEach((comment,j)=>{
                comment.author=commentAuthors[i][j];
            });
        });

        posts.forEach((post,i)=>{
            post.author=authors[i];
            post.comments=comments[i];
        });

        return ret;
    },

    getList:async (query,fields,opts)=>{
        let {total,page,limit,posts}=await Post.page(query,Object.assign({__v:false,content:false,archive:false},fields),opts);
        let authors=await Promise.all(posts.map(post=>User.findOne({_id:post.author},{name:true})));
        posts.forEach((post,i)=>{
            post.author=authors[i];
        });
        return {total,page,limit,posts};
    },

    getAPIPosts:async (query,fields,opts)=>{
        let {total,page,limit,posts}=await Post.page(query,Object.assign({__v:false,archive:false,comments:false,reprintUsers:false},fields),opts);
        let authors=await Promise.all(posts.map(post=>User.findOne({_id:post.author},{name:true,avatar:true})));
        posts=posts.map((post,i)=>{
            let topic=_.pick(post,'_id','title','tags','intro','content','time','pv');
            topic.author={
                name:authors[i].name,
                avatar_url:config.avatarCDN+'/'+authors[i].avatar+'?v=3&s=120'
            }
            return topic;
        });
        return {total,page,limit,posts};
    }
};